#include "../head/DemoduleUtil.h"
#include <QDateTime>
#include <QMessageBox>
#include <QTextStream>

DemoduleUtil::DemoduleUtil()
{

}

void DemoduleUtil::initParam()
{
    fifoReceiver.Buf = (double*)malloc(RECEIVE_BUF_SIZE * sizeof(double));
    DataPrimary = (double*)malloc(1000 * sizeof(double));
    time_t timep;
    struct tm* nowtime;
    char logFilePath[256] = { 0 };
    time(&timep);						//获取从1970至今过了多少秒，存入time_t类型的timep
    nowtime = localtime(&timep);		//用localtime将秒数转化为struct tm结构体
    sprintf_s(logFilePath, 256, "../../../%d%02d%02d_%02d%02d.log", 1900 + nowtime->tm_year, 1 + nowtime->tm_mon, nowtime->tm_mday, nowtime->tm_hour, nowtime->tm_min);//把格式化的时间写入字符数组中
    FOPEN(logfile, logFilePath, "wt+");	//保存 log信息，在程序结束时closefile

    INIFileStream = OpenINIFile("F:\\qt_word\\20221201\\20221201\\InitParam.ini");

    if (INIFileStream == NULL)
    {
        printf("OPEN FAILED!!1");
        ERROR(INIFileStream);
    }

    DemodParam = (PtrDemodParam)malloc(sizeof(VarDemodParam));
    DemodulatorParamSet(INIFileStream, C_DATA_FRAME_LEN_BIT, PressureSensorNum, &Fc_Hz_read, &Rb_bps_read, &ModuleEnableStatus, DemodParam);

    if (Fc_Hz < 1 || Fc_Hz>30)
    {
        //fprintf(logfile, "Warning!!! Fc_Hz=%g replaced by Fc_Hz_read=%g !\n", Fc_Hz, Fc_Hz_read);
        Fc_Hz = Fc_Hz_read;
    }
    if (Rb_bps < 1 || Rb_bps>10)
    {
        //fprintf(logfile, "Warning!!! Rb_bps=%g replaced by Rb_bps_read=%g !\n", Rb_bps, Rb_bps_read);
        Rb_bps = Rb_bps_read;
    }



    DataPumpStroke_d = (double*)malloc(DemodParam->ADC_Fs_Hz * sizeof(double));
    memset(DataPumpStroke_d, 0, DemodParam->ADC_Fs_Hz * sizeof(double));

    DecData = (double*)malloc(2 * (DemodParam->TRAINING_SEQ_LEN + MAX_RBPS) * sizeof(double));
    memset(DecData, 0, 2 * (DemodParam->TRAINING_SEQ_LEN + MAX_RBPS) * sizeof(double));

    mseqIndicator = (double*)malloc(2 * (DemodParam->TRAINING_SEQ_LEN) * sizeof(double));
    memset(mseqIndicator, 0, 2 * (DemodParam->TRAINING_SEQ_LEN) * sizeof(double));


    //为结构体指针分配内存

    DemodulatorS_PriCh = (PtrDemodulatorStruct)malloc(sizeof(VarDemodulatorStruct));

    DemodulatorS_PriCh->PreFilterStructRef = NULL;//单通道 此部分结构体指针为空指针  双通道此部分结构体指针分配内存
    DemodulatorS_PriCh->DecimatorStructRef = NULL;
    DemodulatorS_PriCh->DSNC_Struct = NULL;

    DemodulatorS_PriCh->PreFilterStruct = (PtrPreFilterStruct)malloc(sizeof(VarPreFilterStruct));
    DemodulatorS_PriCh->PreFilterStruct1 = (PtrPreFilterStruct)malloc(sizeof(VarPreFilterStruct));
    DemodulatorS_PriCh->FpumpMeasureStruct = (PoPumpStruct)malloc(sizeof(VarPumpStruct));
    DemodulatorS_PriCh->DecimatorStruct = (PtrDecimator)malloc(sizeof(VarDecimator));
    DemodulatorS_PriCh->DecimatorStruct1 = (PtrDecimator)malloc(sizeof(VarDecimator));

    DemodulatorS_PriCh->BPSK_DemodStruct = (PtrBPSKDemodStruct)malloc(sizeof(VarBPSKDemodStruct));
    DemodulatorS_PriCh->ModuleStructFSRC = (PtrFarrowStruct)malloc(sizeof(VarFarrowStruct));
    DemodulatorS_PriCh->CarrierDPLLStruct = (PtrCarrierDPLLStruct)malloc(sizeof(VarCarrierDPLLStruct));
    DemodulatorS_PriCh->ModuleStructFrameSync = (PtrFrameSyncStruct)malloc(sizeof(VarFrameSyncStruct));
    DemodulatorS_PriCh->ModuleStructFrameSyncBuf = (PtrBufStruct)malloc(sizeof(VarBufStruct));
    DemodulatorS_PriCh->ModuleStructEq = (PrtEqualizerDFEStruct)malloc(sizeof(VarEqualizerDFEStruct));
    DemodulatorS_PriCh->ChirpDetectionStruct = (PtrChirpDetectionStruct)malloc(sizeof(VarChirpDetectionStruct));//ADD chirp检测
    DemodulatorS_PriCh->MedFilterStruct = (PtrMedFilterStruct)malloc(sizeof(VarMedFilterStruct));//ADD MedFilter

    //2022.12.01


    Probe = (PtrProbe)malloc(sizeof(VarProbe));
    memset(Probe, 0, sizeof(VarProbe));

    MudSigStand = (PtrMudSig)malloc(sizeof(VarMudSig));
    memset(MudSigStand, 0, sizeof(VarMudSig));

    //为泥浆脉冲信号分配内存
    MudSigStand->Pri = NULL;
    MudSigStand->Ref = NULL;
    MudSigStand->Pri = NEW(DemodParam->ADC_Fs_Hz, double);
    MudSigStand->Ref = NEW(DemodParam->ADC_Fs_Hz, double);

    //模块初始化
    DemodulatorInit(INIFileStream, Fc_Hz, Rb_bps, DemodulatorS_PriCh, DemodParam, ModuleEnableStatus);

    if (!CloseINIFile(INIFileStream))//文件使用完毕，
    {
        printf("\nclose file faild!\n");
    }

    //为Probe里的指针动态分配内存
    Probe->SigBB_Frw = NEW(2 * (DemodulatorS_PriCh->ModuleStructFSRC->Farrow_SigLen), double);//经过初始化后为Farrow_SigLen赋值z
    Probe->SyncedSigOut = NEW(2 * (DemodulatorS_PriCh->ModuleStructFSRC->Farrow_SigLen), double);
    Probe->MseqCorrOut = NEW(DemodulatorS_PriCh->ModuleStructFSRC->Farrow_SigLen, double);
    Probe->FrameSyncSig = NEW(DemodulatorS_PriCh->ModuleStructFSRC->Farrow_SigLen, int);
    Probe->CarrierLocI = NEW(DemodulatorS_PriCh->ModuleStructFSRC->Farrow_SigLen, double);
    Probe->CarrierLocQ = NEW(DemodulatorS_PriCh->ModuleStructFSRC->Farrow_SigLen, double);
    Probe->SigBB_AFC = NEW(2 * (DemodulatorS_PriCh->ModuleStructFSRC->Farrow_SigLen), double);
    Probe->EqSig = NEW(2 * ((DemodParam->TRAINING_SEQ_LEN) + MAX_RBPS), double);
    Probe->DecData = NEW(2 * ((DemodParam->TRAINING_SEQ_LEN) + MAX_RBPS), double);
    Probe->EqErr = NEW(2 * ((DemodParam->TRAINING_SEQ_LEN) + MAX_RBPS), double);
    Probe->SigPreFilt = NEW(DemodParam->ADC_Fs_Hz, double);
    Probe->SigMedFilt = NEW(DemodParam->ADC_Fs_Hz, double);
    Probe->SignalDenoise = NEW(DemodParam->ADC_Fs_Hz, double);


    //打开信号文件
    //printf("reading signal file ...\n");
    //fileseek = 7993 * 1000;           //925  2019-07-09_19-32-40 BPSK - 8.00bps@24.00Hz
}


void DemoduleUtil::demodule(){
for (int i = 0; i < DemodParam->ADC_Fs_Hz; i++)
{
    MudSigStand->Pri[i] = DataPrimary[i];
}

//解调地面数据
Demodulator(MudSigStand, DataPumpStroke_d, DemodulatorS_PriCh, 0, 0, ModuleEnableStatus, DFE_perFrameResetEna, DecData, mseqIndicator, Probe, DemodParam, DecDataBufCnt);

    for (int i = 0; i < Actual_Len / 2; i++)
    {
        SigBB_Frw_PriCh_Temp_I.append(Probe->SigBB_Frw[2 * i]);
        SigBB_Frw_PriCh_Temp_Q.append(Probe->SigBB_Frw[2 * i + 1]);

        CarrierLocI_PriCh_Temp_I.append(Probe->CarrierLocI[i]);
        CarrierLocI_PriCh_Temp_Q.append(Probe->CarrierLocQ[i]);

        FrameSync_PriCh_Temp.append(Probe->FrameSyncSig[i]);
        MseqCorrOut_PriCh_Temp.append(Probe->MseqCorrOut[i]);

        if(SigBB_Frw_PriCh_Temp_I.size() > RECEIVE_BUF_SIZE_COUNT * RECEIVE_BUF_SIZE){
            SigBB_Frw_PriCh_Temp_I.removeFirst();
            SigBB_Frw_PriCh_Temp_Q.removeFirst();
        }
    }


    for (int i = 0; i < Probe->EqSigCnt; i++)
    {
        EqSig_PriCh_Temp_I.append(Probe->EqSig[i * 2]);
        EqSig_PriCh_Temp_Q.append(Probe->EqSig[i * 2 + 1]);
        EqErr_PriCh_Temp.append(sqrt(pow(Probe->EqErr[i * 2], 2) + pow(Probe->EqErr[i * 2 + 1], 2)));

        if(EqSig_PriCh_Temp_I.size() > RECEIVE_BUF_SIZE_COUNT * RECEIVE_BUF_SIZE){
            EqSig_PriCh_Temp_I.removeFirst();
            EqSig_PriCh_Temp_Q.removeFirst();
            EqErr_PriCh_Temp.removeFirst();
        }
    }

    double training_seq_temp[31];
    for (int i = 0; i < 31; i++)  {
        training_seq_temp[i] = DemodParam->TRAINING_SEQ[30 - i];
    }
    for (int i = 0; i < DemodParam->ADC_Fs_Hz; i++)
    {
        DataPrimary_Temp.append(DataPrimary[i]);

        SigPreFilt_PriCh_Temp.append(Probe->SigPreFilt[i]);

        if(DataPrimary_Temp.size() > RECEIVE_BUF_SIZE_COUNT * RECEIVE_BUF_SIZE){
            DataPrimary_Temp.removeFirst();
            SigPreFilt_PriCh_Temp.removeFirst();
        }
    }

    if(step == RECEIVE_BUF_SIZE_COUNT){ // 接收20帧清空
        saveSourceFile();
        step = 0;

        listSource.clear();


//        DataPrimary_Temp.clear();
//        SigPreFilt_PriCh_Temp.clear();
//        SigBB_Frw_PriCh_Temp_I.clear();
//        SigBB_Frw_PriCh_Temp_Q.clear();
//        CarrierLocI_PriCh_Temp_I.clear();
//        CarrierLocI_PriCh_Temp_Q.clear();
//        FrameSync_PriCh_Temp.clear();
//        MseqCorrOut_PriCh_Temp.clear();
//        EqSig_PriCh_Temp_1_I.clear();
//        EqSig_PriCh_Temp_2_I.clear();
//        EqSig_PriCh_Temp_3_I.clear();
//        EqSig_PriCh_Temp_1_Q.clear();
//        EqSig_PriCh_Temp_2_Q.clear();
//        EqSig_PriCh_Temp_3_Q.clear();
//        EqSig_PriCh_Temp_I.clear();
//        EqSig_PriCh_Temp_Q.clear();
//        c_m_seq.clear();
//        DecodedData_Temp.clear();
//        EqErr_PriCh_Temp.clear();
    }
    step = step + 1;

}

void DemoduleUtil::freeParam()
{
    free(DataPrimary);
    free(fifoReceiver.Buf);
    free(DataPumpStroke_d);
    free(DecData);
    free(DataPrimary_buffer);
    free(SigPreFilt_PriCh_buffer);
    free(SignalDenoise_PriCh_buffer);
    free(SigBB_PriCh_buffer);
    free(SigBB_Frw_PriCh_buffer);
    free(SyncedSigOut_PriCh_buffer);
    free(MseqCorrOut_PriCh_buffer);
    free(FrameSync_PriCh_buffer);
    free(CarrierLocI_PriCh_buffer);
    free(CarrierLocQ_PriCh_buffer);
    free(SigBB_AFC_PriCh_buffer);
    free(EqSig_PriCh_buffer);
    free(DecData_PriCh_buffer);
    free(EqErr_PriCh_buffer);

    //释放结构体动态内存
    DemodulatorDelete(DemodulatorS_PriCh, Probe, MudSigStand, DemodParam, ModuleEnableStatus);

    fclose(logfile);
}

void DemoduleUtil::saveSourceFile(){
    //存TEXT文件
        QDateTime curDateTime = QDateTime::currentDateTime();
        QFile Save_Text_File(baseUrl+curDateTime.toString("yyyy-MM-dd")+".txt");
        if (!Save_Text_File.open(QIODevice::WriteOnly|QIODevice::Append))//|QIODevice::Text可以适应本地系统，解决回车问题  \r   \r\n
        {
            QMessageBox::about(NULL,"错误", "未找到文件!");
        }
        QTextStream txtOutput(&Save_Text_File);

        txtOutput << "Record Datetime:"<< curDateTime.toString(" yyyy-MM-dd hh:mm:ss");
        txtOutput << "\n";
        for (int i = 0;i < listSource.size(); i++) {
            txtOutput <<listSource[i] << "";

        }
        txtOutput << "\n";
        Save_Text_File.close();





}

